package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.ExerciseMapper;
import com.itheima.pojo.Exercise;
import com.itheima.service.ExerciseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = ExerciseService.class)
@Transactional
public class ExerciseServiceImpl implements ExerciseService {
    @Autowired
    private ExerciseMapper exerciseMapper;
    //向膳食表中导入数据
    @Override
    public void add(ArrayList<Exercise> exerciseList) {
        for (Exercise exercise : exerciseList) {
            //根据运行信息查找是否有这条运动数据
            String name = exercise.getName();
            //运动名称非空
            if (name!=null&&name.length()>0) {
                Integer count = exerciseMapper.findCountByExerciseName(name);
                if (count > 0) {
                    //查找到进行修改操作
                    exerciseMapper.update(exercise);
                } else {
                    //没有查找到进行添加
                    exerciseMapper.add(exercise);
                }
            }
        }
    }
    //分页查询功能
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        //获取页码
        Integer currentPage = queryPageBean.getCurrentPage();
        //获取每页显示条数
        Integer pageSize = queryPageBean.getPageSize();
        //获取查询条件
        String queryString = queryPageBean.getQueryString();

        //分页插件进行分页
        PageHelper.startPage(currentPage,pageSize);
        //调用持久层的方法
        Page<Exercise> page = exerciseMapper.findByPage(queryString);
        //返回集合
        List<Exercise> list = page.getResult();
        long total = page.getTotal();
        return new PageResult(total, list);
    }
    //获取当前页数据
    @Override
    public List<Exercise> findCurrentPage(QueryPageBean queryPageBean) {
        //获取页码
        Integer currentPage = queryPageBean.getCurrentPage();
        //获取每页显示条数
        Integer pageSize = queryPageBean.getPageSize();
        //获取查询条件
        String queryString = queryPageBean.getQueryString();
        //分页插件进行分页
        PageHelper.startPage(currentPage,pageSize);
        //调用持久层的方法
        Page<Exercise> page = exerciseMapper.findByPage(queryString);
        //返回集合
        return page.getResult();

    }
    //根据id删除功能
    @Override
    public void deleteById(Integer id) {
         exerciseMapper.deleteById(id);;
    }

    @Override
    public List<Exercise> findAll() {
        return exerciseMapper.findAll();
    }
}
